package logger

import (
	"errors"
	"fmt"
	"time"

	"github.com/sirupsen/logrus"
)

// ExampleUsage demonstrates how to use the logger module in different scenarios
func ExampleUsage() {
	// Initialize logger with custom configuration
	config := &Config{
		Level:  LevelDebug,
		Format: FormatJSON,
		Output: "stdout",
	}
	Init(config)

	// Basic logging
	Info("Application starting")
	Debug("Debug information")
	Warn("Warning message")
	Error("Error occurred")

	// Logging with error
	err := errors.New("connection failed")
	WithError(err).Error("Failed to connect to database")

	// Component-specific logging
	WithComponent("vip-manager").Info("VIP manager initialized")

	// VIP operations - use the global helper functions
	WithVIP("192.168.1.100/24", "eth0").Info("VIP bound successfully")
	WithVIP("192.168.1.100/24", "eth0").Info("VIP unbound")

	// Health check logging
	WithHealthCheck("database", true, "Connection successful").Info("Health check passed")
	WithHealthCheck("web-service", false, "Connection timeout").Warn("Health check failed")

	// Election logging
	WithElection("node-1", 100, 3).Info("New leader elected")
	WithElection("", 0, 2).Warn("Lost quorum, no leader")

	// Network logging
	WithNetwork("udp", "224.0.0.251:9650").Info("Heartbeat sent")
	WithNetwork("grpc", "192.168.1.101:9652").Info("gRPC connection established")

	// Peer logging
	WithPeer("app-01", "192.168.1.11").Info("Peer connected")
	WithPeer("app-02", "192.168.1.12").Warn("Peer disconnected")

	// Complex logging with multiple fields
	WithFields(logrus.Fields{
		"component": "coordinator",
		"node_id":   "app-01",
		"vip":       "192.168.1.100/24",
		"interface": "eth0",
		"priority":  100,
		"healthy":   true,
	}).Info("Node state updated")
}

// ExampleMigration shows how to migrate from direct logrus usage
func ExampleMigration() {
	// Before (direct logrus usage):
	// import "github.com/sirupsen/logrus"
	// logrus.WithError(err).Fatal("failed to start UDP heartbeat")
	// logrus.WithField("vip", m.vipAddr.IPNet).Info("VIP bound successfully")
	// logrus.WithFields(logrus.Fields{
	//     "new_leader": leader,
	//     "priority":   maxP,
	// }).Info("election result")

	// After (using logger module):
	Init(DefaultConfig())

	// Simple error logging
	err := errors.New("UDP heartbeat failed")
	WithError(err).Fatal("failed to start UDP heartbeat")

	// VIP logging with context
	WithVIP("192.168.1.100/24", "eth0").Info("VIP bound successfully")

	// Election logging with structured fields
	WithElection("node-1", 100, 3).Info("election result")
}

// ExampleConfigIntegration shows how to integrate with the main config
func ExampleConfigIntegration() {
	// This would be added to the main Config struct in internal/config/config.go
	type LoggerConfig struct {
		Level  Level  `yaml:"level"`
		Format Format `yaml:"format"`
		Output string `yaml:"output"`
	}

	// Example config.yaml content:
	configYAML := `
# vdrift 配置文件
node_id: app-01
listen:
  udp: 0.0.0.0:9650
  grpc: 0.0.0.0:9652

# Logger configuration
logger:
  level: info
  format: json
  output: stdout

vip: 192.168.1.200/24
interface: eth0
`

	fmt.Println("Example config.yaml with logger section:")
	fmt.Println(configYAML)
}

// ExampleProductionUsage shows production-ready logging patterns
func ExampleProductionUsage() {
	// Production configuration
	config := &Config{
		Level:  LevelInfo,             // Only log info and above in production
		Format: FormatJSON,            // Structured logging for log aggregation
		Output: "/var/log/vdrift.log", // Log to file
	}
	Init(config)

	// Application lifecycle logging
	WithComponent("main").Info("vdrift starting")
	defer WithComponent("main").Info("vdrift shutting down")

	// Error handling with context
	func() {
		defer func() {
			if r := recover(); r != nil {
				WithComponent("main").
					WithField("panic", r).
					Error("Application panic recovered")
			}
		}()

		// Simulate some work
		WithComponent("worker").Info("Processing request")
	}()

	// Performance logging
	start := time.Now()
	// ... do work ...
	duration := time.Since(start)
	WithComponent("performance").
		WithField("duration_ms", duration.Milliseconds()).
		Info("Operation completed")
}

// ExampleStructuredLogging shows advanced structured logging patterns
func ExampleStructuredLogging() {
	Init(&Config{
		Level:  LevelDebug,
		Format: FormatJSON,
		Output: "stdout",
	})

	// Request/response logging
	WithFields(logrus.Fields{
		"request_id":  "req-123",
		"method":      "POST",
		"endpoint":    "/api/v1/state",
		"duration_ms": 45,
		"status_code": 200,
	}).Info("API request completed")

	// State change logging
	WithFields(logrus.Fields{
		"component": "state-manager",
		"old_state": "healthy",
		"new_state": "degraded",
		"reason":    "database_check_failed",
		"node_id":   "app-01",
	}).Warn("Node state changed")

	// Metrics logging
	WithFields(logrus.Fields{
		"component": "metrics",
		"metric":    "vip_bind_duration",
		"value":     12.5,
		"unit":      "milliseconds",
		"node_id":   "app-01",
	}).Info("Metric recorded")
}
